package com.hrbxlh.doccheck.controller;

import com.hrbxlh.doccheck.domain.SimilarFile;
import com.hrbxlh.doccheck.service.DocCheckService;
import com.hrbxlh.doccheck.vo.SimilarFileVO;
import com.hrbxlh.util.CascaderVO;
import com.hrbxlh.util.DocCheckUtil;
import com.hrbxlh.util.Result;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import static com.hrbxlh.doccheck.constant.DocCheckConstant.MAX_UPLOAD_SIZE;
import static com.hrbxlh.doccheck.constant.DocCheckConstant.MAX_UPLOAD_SIZE_MESSAGE;


/**
 * @author cheer
 */
@RestController
@RequestMapping("/doc-check")
public class DocCheckController {


    @Autowired
    private DocCheckService docCheckService;

    @PostMapping("/upload")
    @ResponseBody
        public Result uploadFile(MultipartFile file,@RequestParam String userId) throws Exception {
        if (file.getSize() > MAX_UPLOAD_SIZE) {
            throw new Exception("上传文件过大");
        }
        docCheckService.uploadFile(userId, file);
        return Result.success();
    }

    @GetMapping("/view")
    @ResponseBody
    public Result<List<CascaderVO>> viewFile(@RequestParam String  userId) {
        List<CascaderVO> fileTree = docCheckService.viewFile(userId);
        return Result.success(fileTree);
    }

    @GetMapping
    @ResponseBody
    public Result<List<SimilarFileVO>> queryFile(@RequestParam Double similarity,@RequestParam String userId) {
        List<SimilarFile> similarFiles = docCheckService.querySimilarFile(userId, similarity);

        List<SimilarFileVO> similarFileVOs = new ArrayList<>();

        if (CollectionUtils.isNotEmpty(similarFiles)) {
            DecimalFormat df = new DecimalFormat("0.00%");
            for (SimilarFile similarFile : similarFiles) {
            	SimilarFileVO svo=new SimilarFileVO();
            	svo.setFile(similarFile.getFile());
            	svo.setComparedFile(similarFile.getComparedFile());
            	svo.setSimilarity(df.format(similarFile.getSimilarityScore()));
                similarFileVOs.add(svo);
            }
        }

        return Result.success(similarFileVOs);
    }
}
